package com.jlkf.service.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Call;
import io.swagger.client.*;
import io.swagger.client.api.AuthenticationApi;
import io.swagger.client.api.ChatRoomsApi;
import io.swagger.client.api.UsersApi;
import io.swagger.client.model.ModifyChatroom;
import io.swagger.client.model.RegisterUsers;
import io.swagger.client.model.Token;
import io.swagger.client.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @author he.hb
 * 环信工具类
 */
@Component
public class EmChatRestUtil {

    protected static Logger logger = LoggerFactory.getLogger(EmChatRestUtil.class);

  
    static ResourceBundle rb =  ResourceBundle.getBundle("config", Locale.CHINA);
    static String orgName =rb.getString("API_ORG");
    static String appName =rb.getString("API_APP"); 
    static String clientSecret =rb.getString("APP_CLIENT_SECRET");
    static String clientId =rb.getString("APP_CLIENT_ID");
    static String grantType=rb.getString("grant_type");
/*    @Value("${emchat.orgname}")
    private String orgName;
    @Value("${emchat.appname}")
    private String appName;
    @Value("${emchat.granttype}")
    private String grantType;
    @Value("${emchat.clientid}")
    private String clientId;
    @Value("${emchat.clientsecret}")
    private String clientSecret;*/

    //获取token
    public static String getToken() {
        AuthenticationApi apiInstance = new AuthenticationApi();
        Token body = new Token().clientId(clientId).grantType(grantType).clientSecret(clientSecret);
        try {
            String result = apiInstance.orgNameAppNameTokenPost(orgName, appName, body);
            logger.info("环信获取token：" + result);
            Gson gson = new Gson();
            Map map = gson.fromJson(result, Map.class);
            return " Bearer " + map.get("access_token");
        } catch (ApiException e) {
            logger.error("环信获取token：" + "Exception when calling AuthenticationApi#orgNameAppNameTokenPost");
            e.printStackTrace();
        }
        return null;
    }

    //注册用户
    public static boolean  register(User user) {
        UsersApi apiInstance = new UsersApi();
        RegisterUsers body = new RegisterUsers();
        body.add(user);
        String authorization = getToken();
        try {
            String result = apiInstance.orgNameAppNameUsersPost(orgName, appName, body, authorization);
            Gson gson = new Gson();
            Map map = gson.fromJson(result, Map.class);
            if (map.get("entities") != null) {
                return true;
            } else {
                logger.error("环信注册错误信息：" + gson.toString());
            }
        } catch (ApiException e) {
            logger.error("环信注册用户:" + "Exception when calling UsersApi#orgNameAppNameUsersPost");
            e.printStackTrace();
        }
        return false;
    }

    //获取APP所有聊天室
  /*  public  JSONArray getChatrooms() {
        ChatRoomsApi apiInstance = new ChatRoomsApi();
        String authorization = getToken();
        try {
            String result = apiInstance.orgNameAppNameChatroomsGet(orgName, appName, authorization);
            JSONObject json = JSONObject.parseObject(result);
            int i = json.getInteger("count");
            if (i > 0) {
                JSONArray array = json.getJSONArray("data");
                return array;
            }
        } catch (ApiException e) {
            logger.error("获取环信APP所有聊天室："+"Exception when calling ChatRoomsApi#orgNameAppNameChatroomsGet");
            e.printStackTrace();
        }
        return null;
    }

    //修改聊天室
    public boolean updateChatroom(String chatroomId,ModifyChatroom body){
        ChatRoomsApi apiInstance = new ChatRoomsApi();
        String authorization = getToken();
        try {
            String result = apiInstance.orgNameAppNameChatroomsChatroomIdPut(orgName, appName, authorization, chatroomId, body);
            JSONObject json = JSONObject.parseObject(result);
            if(json.getJSONObject("data")!=null){
                return true;
            }
        } catch (ApiException e) {
            logger.error("环信聊天室修改："+"Exception when calling ChatRoomsApi#orgNameAppNameChatroomsChatroomIdPut");
            e.printStackTrace();
        }
        return false;
    }

    //聊天室详情
    public JSONObject chatDetail(String chatroomId){
        ChatRoomsApi apiInstance = new ChatRoomsApi();
        String authorization = getToken();
        try {
            String result = apiInstance.orgNameAppNameChatroomsChatroomIdGet(orgName, appName, authorization, chatroomId);
            JSONObject json = JSONObject.parseObject(result);
            if(json.getJSONObject("data")!=null){
                return json;
            }
        } catch (ApiException e) {
            logger.error("环信聊天室详情："+"Exception when calling ChatRoomsApi#orgNameAppNameChatroomsChatroomIdGet");
            e.printStackTrace();
        }
        return null;
    }
*/
    //分页获取聊天室成员 Path: /{org_name}/{app_name}/chatrooms/{chatroom_id}/users
    /*public JSONObject getChatroomUserPage(String id,Page page){
        String url ="/"+orgName+"/"+appName+"/chatrooms/"+id+"/users?pagenum="+page.getPageNum()+"&pagesize="+page.getPageSize();
        try{
            String result = emAPICopy(url,"GET",null);
            JSONObject json = JSONObject.parseObject(result);
            if(json.get("data")!=null){
                return json;
            }
        }catch (ApiException e){
            logger.error("环信聊天室用户："+e.getMessage());
        }
        return null;
    }
*/
    //聊天室用户禁言 Path: /{org_name}/{app_name}/chatrooms/{chatroom_id}/mute
  /*  public boolean chatroomUserMute(String id,Map<String,Object> params){
        String url ="/"+orgName+"/"+appName+"/chatrooms/"+id+"/mute";
        try{
            String result = emAPICopy(url,"POST",params);
            JSONObject json = JSONObject.parseObject(result);
            if(json.get("data")!=null){
                return true;
            }
        }catch (ApiException e){
            logger.error("环信聊天室用户："+e.getMessage());
        }
        return false;
    }*/




    //****************************************************************************************************************
    /**
     * 官方没有API接口可以直接调用，需要自己构建
     * 根据官方API模仿的接口
     */
    private ApiClient apiClient;
    public EmChatRestUtil(){this(Configuration.getDefaultApiClient());}
    public EmChatRestUtil(ApiClient apiClient){this.apiClient = apiClient;}
    public ApiClient getApiClient() {return apiClient;}
    public void setApiClient(ApiClient apiClient) {this.apiClient = apiClient;}

    //公共请求方法模板
    //url eg:"/{org_name}/{app_name}/chatrooms/{chatroom_id}
    public String emAPICopy(String url,String mothod,Object params) throws ApiException{
        List<Pair> localVarQueryParams = new ArrayList();

        //添加token
        Map<String, String> localVarHeaderParams = new HashMap();
        if (getToken() != null) {
            localVarHeaderParams.put("Authorization", this.apiClient.parameterToString(getToken()));
        }
        //添加参数形式 application/json
        Map<String, Object> localVarFormParams = new HashMap();
        String[] localVarAccepts = new String[]{"application/json"};
        String localVarAccept = this.apiClient.selectHeaderAccept(localVarAccepts);
        if (localVarAccept != null) {
            localVarHeaderParams.put("Accept", localVarAccept);
        }
        //响应
        String[] localVarContentTypes = new String[]{"application/json"};
        String localVarContentType = this.apiClient.selectHeaderContentType(localVarContentTypes);
        localVarHeaderParams.put("Content-Type", localVarContentType);

        //删了一大段，如果不通，可以看看参考
        String[] localVarAuthNames = new String[0];
        Call call = this.apiClient.buildCall(url, mothod, localVarQueryParams, params, localVarHeaderParams,
                localVarFormParams, localVarAuthNames, (ProgressRequestBody.ProgressRequestListener)(null));
        Type localVarReturnType = (new TypeToken<String>() {}).getType();
        return (String)this.apiClient.execute(call, localVarReturnType).getData();
    }
}
